package com.example.hospital.api.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.example.hospital.api.common.R;
import com.example.hospital.api.common.exception.AccountNotFoundException;
import com.example.hospital.api.common.handler.ExceptionEnum;
import com.example.hospital.api.common.vo.LoginVo;
import com.example.hospital.api.db.dao.MisUserDao;
import com.example.hospital.api.service.MisUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MisUserServiceImpl implements MisUserService {

    @Resource
    private MisUserDao misUserDao;

    @Override
    public LoginVo login(Map<String, String> param) {
        String username = MapUtil.getStr(param, "username");
        String password = MapUtil.getStr(param, "password");
        MD5 md5 = MD5.create();
        String temp = md5.digestHex(username);
        //前六位字符
        String tempStart = StrUtil.subWithLength(temp,0,6);
        //后三位
        String tempEnd = StrUtil.subWithLength(temp, 0, -3);
        //混淆原始密码并且加密
        password = md5.digestHex(tempStart + password + tempEnd);
        param.replace("password", password);
        log.info("password:" + password);
        Integer userId = misUserDao.login(param);
        if(userId != null){
            StpUtil.login(userId);
            String token = StpUtil.getTokenValue();
            List<String> permissions = StpUtil.getPermissionList();

            LoginVo loginVo = new LoginVo();
            loginVo.setPermissions(permissions);
            loginVo.setToken(token);
            return loginVo;
        }else {
            throw new AccountNotFoundException(ExceptionEnum.NOT_FOUND);
        }
    }
}
